package com.wzapp.sitposture.common.util;


import com.alibaba.fastjson.JSONObject;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

public class AddressUtil {

    private static final Logger log = LoggerFactory.getLogger(AddressUtil.class);

    private static final String IP_API = "http://ip.taobao.com/service/getIpInfo.php";

    /**
     * @param args
     */
    public static void main(String[] args) {

        String ip = "47.100.196.47";

        String city = null;

        try {
            city = getAddressFromToolIp(ip);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        log.info("结果：" + city);
    }

    /**
     * 获取地址
     *
     * @param ip
     * @return
     * @throws Exception
     */
    public static String getAddressBy126(String ip) {

        try {
            String url = "http://ip.ws.126.net/ipquery?ip=" + ip;

            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            int httpCode = response.code();
            String resultStr = response.body().string();

            log.info("=====" + url);
            log.info("httpCode" + httpCode + "/r/n" + resultStr);
            if (httpCode != 200) {
                return null;
            }

            log.info("从126获取城市成功==========");
            int beginIndex = resultStr.indexOf("lc=") + 4;
            int endIndex = resultStr.indexOf(";") - 1;
            String city = resultStr.substring(beginIndex, endIndex);
            city = city.replace("市", "");

            if (StringUtils.isEmpty(city)) {
                city = "南京";
                log.error("未获取到城市：ip{},默认设置城市为{}", ip, city);
            }
            return city;
        } catch (IOException e) {
            log.error("从126获取城市失败:{}", e.getMessage());
        }

        return null;
    }

    /**
     * 获取地址
     *
     * @param ip
     * @return
     * @throws Exception
     */
    public static String getAddressFromToolIp(String ip) {

        if (null == ip) {
            log.error("ip 不能为空{}", ip);
            return null;
        }
        try {
            String url = "https://tool.lu/ip/ajax.html";

            FormBody body = new FormBody.Builder()
                    .add("ip", ip)
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            int httpCode = response.code();
            String resultStr = response.body().string();

            log.info("=====" + url);
            log.info("httpCode" + httpCode + "/r/n" + resultStr);
            if (httpCode != 200) {
                return null;
            }
            JSONObject result = JSONObject.parseObject(resultStr);
            if (!result.getBoolean("status")) {
                log.error("从toolIp获取ip城市错误");
                return null;
            }
            log.info("从toolIp获取城市成功==========");

            String city = result.getJSONObject("text").getString("tb_location");
            city = city.substring(city.lastIndexOf(" "));
            if (null != city) {
                city = city.trim();
            }
            return city;
        } catch (IOException e) {
            log.error("从toolIp获取城市失败:{}", e.getMessage());
        }

        return null;
    }

    /**
     * 获取地址
     *
     * @param mobile
     * @return
     * @throws Exception
     */
    public static JSONObject getAddressFromToolMobile(String mobile) {

        if (null == mobile) {
            log.error("ip 不能为空{}", mobile);
            return null;
        }
        try {
            String url = "https://tool.lu/mobile/ajax.html";

            //{"status":true,"message":"","text":{"mobile":1708258,"areacode":"0513","province":"\u6c5f\u82cf","city":"\u5357\u901a","postcode":"226000","corp":"\u4e2d\u56fd\u8054\u901a","card":""}}
            FormBody body = new FormBody.Builder()
                    .add("mobile", mobile)
                    .add("operate", "query")
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            int httpCode = response.code();
            String resultStr = response.body().string();

            log.info("=====" + url);
            log.info("httpCode" + httpCode + "/r/n" + resultStr);
            if (httpCode != 200) {
                return null;
            }
            JSONObject result = JSONObject.parseObject(resultStr);
            if (!result.getBoolean("status")) {
                log.error("从toolIp获取ip城市错误");
                return null;
            }
            log.info("从toolIp获取城市成功==========");

            /**
             * {"mobile":1708258,"areacode":"0513","province":"江苏","city":"南通","postcode":"226000","corp":"中国联通","card":""}
             */
            JSONObject detail = result.getJSONObject("text");
            detail.put("mobile", mobile);
            return detail;
        } catch (IOException e) {
            log.error("从toolIp获取城市失败:{}", e.getMessage());
        }

        return null;
    }

    public static String getIpAddressFrom(String ip) {
        String url = "http://www.ip138.com/ips1388.asp?ip=" + ip + "&action=2";
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .header("Content-Type", "text/javascript; charset=utf-8")
                    .build();
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            int httpCode = response.code();
            String resultStr = response.body().string();
            System.out.println(URLDecoder.decode(resultStr));
            System.out.println(resultStr.substring(resultStr.indexOf("</li><li>本站数据："), resultStr.indexOf("市 ")));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
//        return Regex.Replace(GetValueAnd("</li><li>本站数据：", "</li></ul>", strR), "</li><li>", "|", RegexOptions.IgnoreCase);
    }

    public static String getAddressByTaoBao(String params, String encoding) {

        String returnStr = getRs(IP_API, params, encoding);
        JSONObject json = null;

        if (returnStr != null) {
            json = JSONObject.parseObject(returnStr);
            if ("0".equals(json.get("code").toString())) {
                StringBuffer buffer = new StringBuffer();
                //buffer.append(decodeUnicode(json.optJSONObject("data").getString("country")));//国家
                //buffer.append(decodeUnicode(json.optJSONObject("data").getString("area")));//地区
                buffer.append(decodeUnicode(json.getJSONObject("data").getString("region")));//省份
                buffer.append(" ");
                buffer.append(decodeUnicode(json.getJSONObject("data").getString("city")));//市区
//                buffer.append(decodeUnicode(json.getJSONObject("data").getString("county")));//地区
//                buffer.append(decodeUnicode(json.getJSONObject("data").getString("isp")));//ISP公司

                log.debug("===========" + buffer.toString());

                return buffer.toString();

            } else {
                return "获取地址失败";
            }
        }

        return null;
    }

    /**
     * 从url获取结果
     *
     * @param path
     * @param params
     * @param encoding
     * @return
     */
    private static String getRs(String path, String params, String encoding) {

        URL url = null;
        HttpURLConnection connection = null;

        try {
            url = new URL(path);
            connection = (HttpURLConnection) url.openConnection();// 新建连接实例
            connection.setConnectTimeout(2000);// 设置连接超时时间，单位毫秒
            connection.setReadTimeout(2000);// 设置读取数据超时时间，单位毫秒
            connection.setDoInput(true);// 是否打开输出? true|false
            connection.setDoOutput(true);// 是否打开输入流true|false
            connection.setRequestMethod("POST");// 提交方法POST|GET
            connection.setUseCaches(false);// 是否缓存true|false
            connection.connect();// 打开连接端口

            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes(params);
            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), encoding));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            return buffer.toString();
        } catch (Exception e) {
            log.error("从淘宝获取城市错误：{}", e.getMessage());
        } finally {
            if (null!=connection){
                // 关闭连接
                connection.disconnect();
            }
        }

        return null;
    }

    /**
     * 字符转码
     *
     * @param theString
     * @return
     */
    private static String decodeUnicode(String theString) {

        char aChar;
        int len = theString.length();
        StringBuffer buffer = new StringBuffer(len);

        for (int i = 0; i < len; ) {
            aChar = theString.charAt(i++);
            if (aChar == '\\') {
                aChar = theString.charAt(i++);

                if (aChar == 'u') {
                    int val = 0;

                    for (int j = 0; j < 4; j++) {
                        aChar = theString.charAt(i++);

                        switch (aChar) {
                            case '0':
                            case '1':
                            case '2':
                            case '3':
                            case '4':
                            case '5':
                            case '6':
                            case '7':
                            case '8':
                            case '9':
                                val = (val << 4) + aChar - '0';
                                break;
                            case 'a':
                            case 'b':
                            case 'c':
                            case 'd':
                            case 'e':
                            case 'f':
                                val = (val << 4) + 10 + aChar - 'a';
                                break;
                            case 'A':
                            case 'B':
                            case 'C':
                            case 'D':
                            case 'E':
                            case 'F':
                                val = (val << 4) + 10 + aChar - 'A';
                                break;
                            default:
                                throw new IllegalArgumentException("Malformed encoding.");
                        }
                    }

                    buffer.append((char) val);
                } else {
                    if (aChar == 't') {
                        aChar = '\t';
                    }

                    if (aChar == 'r') {
                        aChar = '\r';
                    }

                    if (aChar == 'n') {
                        aChar = '\n';
                    }

                    if (aChar == 'f') {
                        aChar = '\f';
                    }

                    buffer.append(aChar);
                }
            } else {
                buffer.append(aChar);
            }
        }

        return buffer.toString();
    }
}
